import axios, { AxiosRequestConfig, AxiosRequestHeaders, AxiosResponse,AxiosInstance } from 'axios';
import { useUserStore } from "../store/user";
import { layer } from '@layui/layui-vue';
import router from '../router'
import MyProcess from './MyProcess'; 
import MyWin from './MyWin'; 

type TMyAxiosOption = {
    timeout: number;
    baseURL: string;
    showProcess:boolean,
    showError:boolean,
    url:string,
    showProcessshade:boolean,
    token:string,
    returnErr:boolean
}


interface PageQmInterface  {
    page: number;
    pageSize: number; 
}


interface HttpResultInterface  {
    code:number;
    msg: string;
    data: any; 
}

interface RowDataInterface  {     
    rowNo: number; 
}
interface PageDataInterface  {
    records: Array<RowDataInterface>;
    totalRow: number; 
    totalPage: number; 
}


const config: TMyAxiosOption = {
    timeout: 10000,
    baseURL: "http://127.0.0.1:7014",
    showProcess:true,
    showProcessshade:false,
    showError:true,
    url:""  ,
    token:"",
    returnErr:false
}
 

class MyHttp {
    public static LayaUrl:string="http://localhost:8085";
    public static ImageUrl:string="http://localhost:8085";
    public constructor(){

    }
    private qm:any;
    public static getBaseURL():string{
        return config.baseURL;
    }
    private   createService(opt:any):AxiosInstance {
      
        const dstobj = Object.assign({},config, opt);
         
        var service = axios.create(dstobj)
        /* 请求拦截 */
        service.interceptors.request.use((config: any) => {
            let token=dstobj.token;

            const userInfoStore = useUserStore();
            if(!token){
                token=userInfoStore.token as string;
            }
            (config.headers as AxiosRequestHeaders).token=token;
            // if (userInfoStore.token) {
            //     (config.headers as AxiosRequestHeaders).token = userInfoStore.token as string
            // } else { 
            //     if(router.currentRoute.value.path!=='/login') { 
            //         router.push('/login');
            //     }
            // }
            if(dstobj.showProcess)
            { 
               
                MyProcess.show(dstobj.showProcessshade);
            } 
            return config
        }, (error: any) => {
            return Promise.reject(error);
        })

        /* 响应拦截 */
       service.interceptors.response.use((response: AxiosResponse<any>) => {
              
            if(dstobj.showProcess)
            {
                MyProcess.hide();
            } 
            var contentType=response.headers["content-type"].toString();
            if(contentType.toLowerCase().indexOf("application/json")>=0){
                if(response.data.code!=0 ){
                    if(response.data.code==401){
                        MyWin.alert("请重新登录",{
                            onOK:()=>{
                                router.push('/login');
                                layer.closeAll()
                            }
                        })
                        return Promise.reject(response.data.msg);
                    }
                     
                    if(dstobj.showError){
                        MyWin.alert("操作失败:"+response.data.msg,{});
                          
                    }
                    if(dstobj.returnErr){
                        return response.data;
                    }else{
                        return Promise.reject(response.data.msg);
                    }                    
                }
                 
            }  
            return response.data;
             
        }, (error: { toString: () => string; code: string; })  => {
            if(dstobj.showProcess)
            {
                MyProcess.hide();
            } 
            if(dstobj.showError){
                let msg:string=error.toString();
 
                if(error.code=="ERR_NETWORK")
                {
                    msg="网络错误";
                }
                if(msg.indexOf("timeout")>=0)
                {
                    msg="请求超时";
                }
                if(msg.indexOf("status code 404")>=0)
                {
                    msg="错误的请求Url";
                }
                MyWin.alert("操作失败:"+msg,{
                    title:"失败消息"
                });
                      
                
            }
            return Promise.reject(error)
        })
        return service;
    }
    public  get<T>(url: string, params?: object,  opt={}): Promise<any> {
        var service =this.createService(opt);
        return service.get(url,{params,...{} });
    }
    public post<T>(url: string, params?: object,  opt={}): Promise<any> {
        url=url.toLowerCase();
        this.qm=params; 
        var service =this.createService(opt);         
        return service.post(url,params,{});            
    } 

    public async page<T>(url: string, params?: object,  opt={},columns?:any,): Promise<any> {
       
        var service =this.createService(opt);
        var r=await service.post(url,params,{}) as any;  
       
        if(r.code==0){
            let qm=params as any ;
            
            if(qm.page> r.data.totalPage&&r.data.totalPage>0 ){
                  qm.page=r.data.totalPage;
                  return this.page(url,params,opt,columns);
              }else{ 
                  let rowNo=(qm.page-1)*qm.pageSize;
                  r.data.records.forEach( (element:any)=>{
                    columns.forEach((col: { calc: (arg0: any) => void; })=>{
                        if( col.calc&&typeof(col.calc)=="function"){
                            col.calc(element);
                        }
                    }); 
                    element.rowNo=++rowNo;
                });
                   
                   
              }
        }   
        return r;
    } 

    public async list<T>(url: string, params?: object,  opt={},columns?:any,): Promise<any> {
        this.qm=params;
        var service =this.createService(opt);
        var r=await service.post(url,params,{}) as any;  
         
        if(r.code==0){
            let rowNo=0;
            r.data.forEach((element: any)=>{
                  columns.forEach((col: { calc: (arg0: any) => void; })=>{
                      if( col.calc&&typeof(col.calc)=="function"){
                          col.calc(element);
                      }
                  })
                  element.rowNo=++rowNo;
            });
        }
        return r;
    } 

 
}

export default MyHttp